package x.trident.core.micro.gateway.config;

import x.trident.core.micro.gateway.config.properties.TridentGatewayProperties;
import x.trident.core.micro.gateway.core.exception.TridentGatewayExceptionHandler;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 网关全局配置
 *
 * @author Seven
 * @date 2017-11-14-下午5:56
 */
@Configuration
public class ContextConfig {

    /**
     * 全局错误拦截器
     *
     * @author Seven
     * @date 2019/5/12 21:21
     */
    @Bean
    public TridentGatewayExceptionHandler tridentGatewayExceptionHandler() {
        return new TridentGatewayExceptionHandler();
    }

    /**
     * 跨域过滤器
     *
     * @author Seven
     * @date 2019-06-07 15:02
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }

    /**
     * 网关配置
     *
     * @author Seven
     * @date 2021/5/17 15:46
     */
    @Bean
    @ConfigurationProperties(prefix = "gateway")
    public TridentGatewayProperties tridentGatewayProperties(){
        return new TridentGatewayProperties();
    }

}

